/*
 * @Date: 2024-03-26 17:10:37
 * @LastEditors: bingkui.wu
 * @LastEditTime: 2024-04-02 11:21:03
 * @Description: 文字转语音接口。传入文本，生成音频文件。
 */
import { REQUEST } from '#type/request';
import Response from '@common/Response';
import * as superagent from 'superagent';
import { curTime } from "@common/utils";
import * as fs from "fs";
import * as path from "path";
import { WordSound } from '@models/WordSound';
import { getStat, makeDir } from '@/helper/file';
import { getToken } from '@/serives/token';

const getBuffer = (text: string, token: string): Promise<Buffer> => {
  return new Promise((reoslve) => {
    const url = `https://tsn.baidu.com/text2audio`;
    console.log(curTime(), "调动云接口:text2audio: ", text);
    if(!text) {
      return Response.Error(1001, 'text参数为空');
    }
    superagent.post(url)
      .set('Content-Type', 'application/x-www-form-urlencoded')
      .set('Accept', '*/*')
      .send({
        'tex': text,
        'tok': token,
        'cuid': 'ku4ANK02qlKc9MYx7wMdhoGMCcuFSXgC',
        'ctp': '1',
        'lan': 'zh',
        'spd': '5',
        'pit': '5',
        'vol': '5',
        'per': '1',
        'aue': '3'
      }).end(async (err: any, res: any) => {
        if (err) {
          throw err;
        }
        reoslve(res.body);
      })
  });
}
const root: REQUEST.BASIC = {
  auth: false,
  method: 'post',
  request: async (ctx: any) => {
    return new Promise(async (resolve, reject) => {
      const { text } = ctx.request.body;
      const token = await getToken('SOUND');

      const FILE_PATH = `text-sound/${text}.mp3`;
      const FILE_PATH_WITH_PUBLIC = path.join("public", FILE_PATH);

      const wordSound = await WordSound.findOne({ Text: text }).lean().exec();
      const fileStat = await getStat(FILE_PATH_WITH_PUBLIC);

      if (wordSound && fileStat) {
        // console.log("从数据库返回");
        return resolve(Response.Success(wordSound.SoundUrl));
      }

      await WordSound.deleteOne({ Text: text }).lean().exec();
      const audioBuffer = await getBuffer(text, token);
      console.log("audioBuffer=", audioBuffer);

      await makeDir(path.dirname(FILE_PATH_WITH_PUBLIC));
      // 将Buffer写入到文件
      fs.writeFile(FILE_PATH_WITH_PUBLIC, audioBuffer, (err) => {
        if (err) {
          console.error('Error writing file:', err);
          return reject(Response.Error(1002, 'Error writing file:' + err));
        }
      });
      // 保存到数据库
      await WordSound.create({
        Text: text,
        SoundUrl: FILE_PATH
      });

      resolve(Response.Success(FILE_PATH));
      ;
    });
  }
};

export default root;
